package com.huike.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.business.domain.TbBusiness;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.dto.TbClueDTO;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.constant.Constants;
import com.huike.common.constant.HttpStatus;
import com.huike.common.core.page.TableDataInfo;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.domain.vo.StatisticalConstantVO;
import com.huike.report.mapper.ClueStatisticsMapper;
import com.huike.report.domain.dto.PageParamsDTO;
import com.huike.report.domain.vo.ClueStatisticsListVO;
import com.huike.report.domain.vo.LineChartVo;
import com.huike.report.domain.vo.LineSeriesVo;
import com.huike.report.service.CluesStatisticsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description CluesStatisticsServiceImpl
 * @Author moweihua
 * @Date 2023-10-2023/10/17
 */
@Service
@RequiredArgsConstructor
public class CluesStatisticsServiceImpl implements CluesStatisticsService {
    private final TbClueMapper tbClueMapper;

    private final ClueStatisticsMapper clueStatisticsMapper;

    private final TbAssignRecordMapper tbAssignRecordMapper;
    private final TbActivityMapper tbActivityMapper;

    private final TbBusinessMapper tbBusinessMapper;

    private final TbContractMapper tbContractMapper;

    /**
     * 线索统计新增线索数量报表
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVo cluesStatistics(LocalDate beginCreateTime, LocalDate endCreateTime) {
        // 计算开始时间之前的线索总数
        // 获取开始时间前一日的最大时间
        LocalDateTime beforeDate = LocalDateTime.of(beginCreateTime.minusDays(1), LocalTime.MAX);
        QueryWrapper<TbClue> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("create_time", beforeDate);
        Integer total = tbClueMapper.selectCount(queryWrapper);

        // 日期列表
        List<String> dateList = new ArrayList<>();
        // 新增线索数量，线索总数量列表
        List<LineSeriesVo> series = new ArrayList<>();

        // 每天新增的线索数
        List<Object> everyDayCounts = new ArrayList<>();
        List<Object> everyDayTotals = new ArrayList<>();
        while (!beginCreateTime.equals(endCreateTime)) {
            dateList.add(beginCreateTime.toString());
            beginCreateTime = beginCreateTime.plusDays(1);
            // 获取每天的最小时间
            LocalDateTime begin = LocalDateTime.of(beginCreateTime, LocalTime.MIN);
            // 获取每天的最大时间
            LocalDateTime end = LocalDateTime.of(beginCreateTime, LocalTime.MAX);
            // 统计每天新增线索数量
            QueryWrapper<TbClue> wrapper = new QueryWrapper<>();
            wrapper.between("create_time", begin, end);
            Integer everyDayCount = tbClueMapper.selectCount(wrapper);
            everyDayCounts.add(everyDayCount);
            everyDayTotals.add(total + everyDayCount);
        }
        LineSeriesVo newClues = LineSeriesVo.builder().name(StatisticalConstantVO.NEW_CUSTOMERS).data(everyDayCounts).build();
        LineSeriesVo totalClues = LineSeriesVo.builder().name(StatisticalConstantVO.TOTAL_NEW_CUSTOMERS).data(everyDayTotals).build();
        series.add(newClues);
        series.add(totalClues);
        // 返回数据
        return LineChartVo.builder().xAxis(dateList).series(series).build();
    }

    /**
     * 线索统计明细列表
     * @param pageParamsDTO
     * @return
     */
    @Override
    public TableDataInfo<List<ClueStatisticsListVO>> pageList(PageParamsDTO pageParamsDTO) {
        //开启分页
        PageHelper.startPage(pageParamsDTO.pageNum,pageParamsDTO.pageSize);
        Page<ClueStatisticsListVO> page = clueStatisticsMapper.findByCondition(pageParamsDTO);
        //封装返回结果
        TableDataInfo<List<ClueStatisticsListVO>> listTableDataInfo = new TableDataInfo<>();
        listTableDataInfo.setTotal(page.getTotal());
        listTableDataInfo.setRows(page.getResult());
        listTableDataInfo.setCode(HttpStatus.SUCCESS);
        listTableDataInfo.setMsg("查询成功");
        return listTableDataInfo;


    //     Page<TbClue> tbCluePage = new Page<>(pageParamsDTO.pageNum,pageParamsDTO.pageSize);
    //     //分页查询条件
    //     LambdaQueryWrapper<TbClue> wrapper = new LambdaQueryWrapper<>();
    //     // TODO 模糊查询有问题
    //     wrapper.like(!ObjectUtils.isEmpty(pageParamsDTO.getId()),TbClue::getId,pageParamsDTO.id);
    //     wrapper.like(!ObjectUtils.isEmpty(pageParamsDTO.getDeptId()),TbClue::getId,pageParamsDTO.getDeptId());
    //     wrapper.between(TbClue::getCreateTime,pageParamsDTO.getBeginCreateTime(),pageParamsDTO.getEndCreateTime());
    //     Page<TbClue> tbCluePage1 = tbClueMapper.selectPage(tbCluePage, wrapper);
    //     //将返回的数据补充到List<ClueStatisticsListVO>
    //    List<ClueStatisticsListVO> rows = tbCluePage1.getRecords().stream().map(tbClue -> {
    //         ClueStatisticsListVO clueStatisticsListVO = new ClueStatisticsListVO();
    //         BeanUtils.copyProperties(tbClue,clueStatisticsListVO);
    //         clueStatisticsListVO.setClueStatus(tbClue.getStatus());
    //         clueStatisticsListVO.setClueCreateTime(tbClue.getCreateTime());
    //
    //         //查询归属人，归属部门
    //        LambdaQueryWrapper<TbAssignRecord> wrapper1 = new LambdaQueryWrapper<>();
    //        wrapper1.eq(TbAssignRecord::getAssignId,tbClue.getId());
    //        wrapper1.eq(TbAssignRecord::getType,0);
    //        wrapper1.eq(TbAssignRecord::getLatest,1);
    //        TbAssignRecord tbAssignRecord = tbAssignRecordMapper.selectOne(wrapper1);
    //        if (!ObjectUtils.isEmpty(tbAssignRecord)) {
    //            clueStatisticsListVO.setOwner(tbAssignRecord.getUserName());
    //            clueStatisticsListVO.setDeptId(tbAssignRecord.getDeptId());
    //        }
    //
    //        //补全活动相关信息
    //        TbActivity tbActivity = tbActivityMapper.selectTbActivityById(tbClue.getActivityId());
    //        if (!ObjectUtils.isEmpty(tbActivity)) {
    //            clueStatisticsListVO.setCode(tbActivity.getCode());
    //            clueStatisticsListVO.setInfo(tbActivity.getInfo());
    //        }
    //
    //        //补全转换为商机时间，商机状态
    //        LambdaQueryWrapper<TbBusiness> wrapper3 = new LambdaQueryWrapper<>();
    //        wrapper3.eq(TbBusiness::getClueId,tbClue.getId());
    //        TbBusiness tbBusiness = tbBusinessMapper.selectOne(wrapper3);
    //        if (!ObjectUtils.isEmpty(tbBusiness)) {
    //            clueStatisticsListVO.setBusinessCreateTime(tbBusiness.getCreateTime());
    //            clueStatisticsListVO.setBusinessStatus(tbBusiness.getStatus());
    //        }
    //
    //        //查询合同表，补全成交时间和成交金额
    //        if (!ObjectUtils.isEmpty(tbBusiness)) {
    //            LambdaQueryWrapper<TbContract> wrapper2 = new LambdaQueryWrapper<>();
    //            wrapper2.eq(TbContract::getStatus, StatisticalConstantVO.COMPLETED);
    //            wrapper2.eq(TbContract::getBusinessId,tbBusiness.getId());
    //            TbContract tbContract = tbContractMapper.selectOne(wrapper2);
    //            if (!ObjectUtils.isEmpty(tbContract)) {
    //                clueStatisticsListVO.setContractCreateTime(tbContract.getCreateTime());
    //                clueStatisticsListVO.setOrder(tbContract.getContractOrder().floatValue());
    //            }
    //        }
    //
    //        return clueStatisticsListVO;
    //     }).collect(Collectors.toList());
    //
    //    //封装数据返回
    //     TableDataInfo<List<ClueStatisticsListVO>> tableDataInfo = new TableDataInfo<>();
    //     tableDataInfo.setRows(rows);
    //     tableDataInfo.setMsg("查询成功");
    //     tableDataInfo.setTotal(tbCluePage.getTotal());
    //     tableDataInfo.setCode(HttpStatus.SUCCESS);
    //     return tableDataInfo;
    }

    /**
     * 线索统计线索转换率报表
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public Map<String, Integer> getVulnerabilityMap(LocalDate beginCreateTime, LocalDate endCreateTime) {
        Map<String, Integer> map = new HashMap<>();
        map.put("cluesNums",0);//线索数
        map.put("effectiveCluesNums",0);//有效线索数
        map.put("businessNums",0);//商机数
        map.put("contractNums",0);//合同数
        //获取第一天的最小时间
        LocalDateTime beginTime = LocalDateTime.of(beginCreateTime, LocalTime.MIN);
        //获取最后一天的最大时间
        LocalDateTime endTime = LocalDateTime.of(endCreateTime, LocalTime.MAX);

        //统计线索数
        QueryWrapper<TbClue> wrapper1 = new QueryWrapper<>();
        wrapper1.between("create_time",beginTime,endTime);
        map.put("cluesNums",tbClueMapper.selectCount(wrapper1));

        //统计有效线索数
        wrapper1.ge("status", Integer.valueOf(TbClueDTO.StatusType.TOBUSINESS.getValue()));
        map.put("effectiveCluesNums",tbClueMapper.selectCount(wrapper1));

        //统计商机数
        QueryWrapper<TbBusiness> wrapper = new QueryWrapper<>();
        wrapper.between("create_time",beginTime,endTime);
        map.put("businessNums",tbBusinessMapper.selectCount(wrapper));

        //统计合同
        QueryWrapper<TbContract> wrapper2 = new QueryWrapper<>();
        wrapper.between("create_time",beginTime,endTime);
        map.put("contractNums",tbContractMapper.selectCount(wrapper2));
        return map;
    }
}
